package cn.sirun.com.fca.account.view.impl;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tencent.captchasdk.TCaptchaDialog;
import com.tencent.captchasdk.TCaptchaVerifyListener;
import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.PatternMatchingUtils;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.uikit.ui.widget.IovToolbar;
import com.tencent.cloud.uikit.utils.DialogUtils;
import com.tencent.cloud.uikit.utils.SystemUiUtils;
import com.tencent.cloud.uikit.widget.edittext.LineTwoEditText;
import com.tencent.cloud.uikit.widget.edittext.PhoneMailEditText;

import org.json.JSONException;
import org.json.JSONObject;

import cn.sirun.com.fca.account.R;
import cn.sirun.com.fca.account.constant.AccountActivityConst;
import cn.sirun.com.fca.account.constant.AccountIntentConst;
import cn.sirun.com.fca.account.constant.AccountStatusCode;
import cn.sirun.com.fca.account.constant.CaptchaConst;
import cn.sirun.com.fca.account.constant.RequestParamConst;
import cn.sirun.com.fca.account.model.base.Captcha;
import cn.sirun.com.fca.account.model.base.SubmitPhoneRequest;
import cn.sirun.com.fca.account.model.base.SubmitPhoneResponse;
import cn.sirun.com.fca.account.model.register.SubmitEmailRequest;
import cn.sirun.com.fca.account.presenter.IPhonePresenter;
import cn.sirun.com.fca.account.presenter.impl.PhonePresenter;
import cn.sirun.com.fca.account.uitl.AccountStatusUtils;
import cn.sirun.com.fca.account.uitl.IntentUtils;
import cn.sirun.com.fca.account.view.IPhoneView;

public class PhoneFlowView extends AccountBaseLoadingFlowView<IPhonePresenter>
        implements IPhoneView {

    private ImageView mPhoneIV, mSetpIV;
    private TextView mPhoneTV, mSubmitTV;
    private PhoneMailEditText mPhoneET;

    private String mPhoneNumber;
    private TCaptchaDialog mTCaptchaDialog = null;
    private int mFrom;

    public PhoneFlowView(Activity activity) {
        super(activity);
        mFrom = IntentUtils.getIntentFrom(getActivity().getIntent(), AccountIntentConst.REGISTER);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setUpActionBar();
        initView();
    }


    @Override
    public void onSubmitPhoneResult(BaseResponse<SubmitPhoneResponse> response) {
//        hideLoadingView();
//        int code = response.getCode();
//        if (code == StatusCode.SUCCESS) {
//            Intent intent = Router.fromPath(AccountActivityConst.Path.CAPTCHA);
//            intent.putExtra(AccountIntentConst.FROM, AccountIntentConst.REGISTER);
//            intent.putExtra(AccountIntentConst.TELEPHONE, mPhoneNumber);
//            if (null != response.getData()) {
//                intent.putExtra(AccountIntentConst.COUNT_DOWN, response.getData().getResendTime());
//            } else {
//                intent.putExtra(AccountIntentConst.COUNT_DOWN, CaptchaConst.COUNT_DOWN);
//            }
//            getActivity().startActivity(intent);
//        } else {
//            handleErrorCode(code);
//        }
        handleSubmitAccountResult(response);
    }

    @Override
    public void onSubmitEmialResult(BaseResponse<SubmitPhoneResponse> response) {
//        hideLoadingView();
//        int code = response.getCode();
//        if (code == StatusCode.SUCCESS) {
//            Intent intent = Router.fromPath(AccountActivityConst.Path.CAPTCHA);
//            intent.putExtra(AccountIntentConst.TELEPHONE, mPhoneNumber);
//            if (null != response.getData()) {
//                intent.putExtra(AccountIntentConst.COUNT_DOWN, response.getData().getResendTime());
//            } else {
//                intent.putExtra(AccountIntentConst.COUNT_DOWN, CaptchaConst.COUNT_DOWN);
//            }
//            getActivity().startActivity(intent);
//        } else {
//            handleErrorCode(code);
//        }
        handleSubmitAccountResult(response);
    }

    private void handleSubmitAccountResult(BaseResponse<SubmitPhoneResponse> response) {
        hideLoadingView();
        int code = response.getCode();
        if (code == StatusCode.SUCCESS) {
            Intent intent = Router.fromPath(AccountActivityConst.Path.CAPTCHA);
            intent.putExtra(AccountIntentConst.FROM, mFrom);
            intent.putExtra(AccountIntentConst.TELEPHONE, mPhoneNumber);
            if (null != response.getData()) {
                intent.putExtra(AccountIntentConst.COUNT_DOWN, response.getData().getResendTime());
            } else {
                intent.putExtra(AccountIntentConst.COUNT_DOWN, CaptchaConst.COUNT_DOWN);
            }
            getActivity().startActivity(intent);
        } else {
            handleErrorCode(code);
        }
    }

    private void handleErrorCode(int code) {
        if (AccountStatusCode.NEED_VERIFY == code || AccountStatusCode.NEED_CAPTCHA == code) {
            showCaptchaDialog();
            return;
        }
        AccountStatusUtils.showToast(getActivity(), code);
    }

    @Override
    protected IPhonePresenter createPresenter() {
        return new PhonePresenter();
    }

    private void setUpActionBar() {

        final IovToolbar toolbar = SystemUiUtils.showActionBar(
                getActivity(), "");
        if (mFrom == AccountIntentConst.REGISTER) {
            toolbar.setHomeAsUpText(R.string.tv_title_back);
        }

    }

    private void initView() {
        this.setContentView(R.layout.register_phone_activity);
        final Activity activity = getActivity();
        mPhoneIV = activity.findViewById(R.id.iv_phone_prompt);
        mPhoneTV = activity.findViewById(R.id.tv_phone);
        mSubmitTV = activity.findViewById(R.id.tv_submit_phone);
        mPhoneET = activity.findViewById(R.id.et_phone_number);
        mSetpIV = activity.findViewById(R.id.iv_step_one);

        mPhoneET.setTextChangeListener(new LineTwoEditText.OnTextChangeListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    hanldeErrorNotice(false, ResourcesUtils.getString(R.string.tv_title_phone_mail2));
                }
            }
        });

        mSubmitTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkInputString();
            }
        });

        initData();
    }

    private void initData() {
        if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
            mSetpIV.setVisibility(View.GONE);
        }
    }

    private void checkInputString() {
        mPhoneNumber = mPhoneET.getText().toString();
        if (TextUtils.isEmpty(mPhoneNumber)) {
//            DialogUtils.showToast(getActivity(), R.string.input_telephone);
            return;
        }

        boolean isPhoneOrEmailCorrect = PatternMatchingUtils.isTelephoneOrEmailCorrect(mPhoneNumber);
        if (!isPhoneOrEmailCorrect) {
            hanldeErrorNotice(true, ResourcesUtils.getString(R.string.tv_pnone_notice));
        } else {
            hanldeErrorNotice(false, ResourcesUtils.getString(R.string.tv_title_phone_mail2));

//            Intent intent = Router.fromPath(AccountActivityConst.Path.CAPTCHA);
//            intent.putExtra(AccountIntentConst.TELEPHONE, mPhoneNumber);
//            intent.putExtra(AccountIntentConst.COUNT_DOWN, CaptchaConst.COUNT_DOWN);
//            ActivityUtils.startActivityForResult(getActivity(), intent);

            handlePhoneOrEmailSendRequest("", "");

        }
    }

    private void handlePhoneOrEmailSendRequest(String randStr, String ticket) {
        boolean isPhone = PatternMatchingUtils.isTelephoneCorrect(mPhoneNumber);
        if (isPhone) {
            String nation = RequestParamConst.DEFAULT_NATION_CODE;
            SubmitPhoneRequest request;
            if (TextUtils.isEmpty(randStr) || TextUtils.isEmpty(ticket)) {
                request = new SubmitPhoneRequest(nation, mPhoneNumber);
            } else {
                Captcha captcha = new Captcha(randStr, ticket);
                request = new SubmitPhoneRequest(nation, mPhoneNumber, captcha);
            }
            if (mFrom == AccountIntentConst.REGISTER) {
                getPresenter().submitPhone(request);
            } else if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
                getPresenter().resetSubmitPhone(request);
            }
        } else {
            SubmitEmailRequest request;
            if (TextUtils.isEmpty(randStr) || TextUtils.isEmpty(ticket)) {
                request = new SubmitEmailRequest(mPhoneNumber);
            } else {
                request = new SubmitEmailRequest(mPhoneNumber, new Captcha(randStr, ticket));
            }
            if (mFrom == AccountIntentConst.REGISTER) {
                getPresenter().submitEmail(request);
            } else if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
                getPresenter().resetSubmitEmail(request);
            }
        }
        showLoadingView();
    }

    private void hanldeErrorNotice(boolean isShow, String notice) {
        if (isShow) {
            mPhoneIV.setVisibility(View.VISIBLE);
            mPhoneTV.setTextColor(ResourcesUtils.getColor(R.color.login_register_text_color));
            mPhoneTV.setText(notice);
        } else {
            mPhoneIV.setVisibility(View.GONE);
            mPhoneTV.setTextColor(ResourcesUtils.getColor(R.color.login_input_text_color));
            mPhoneTV.setText(notice);
        }
    }

    private void showCaptchaDialog() {
        mTCaptchaDialog = new TCaptchaDialog(getActivity(), CaptchaConst.APP_ID, new
                TCaptchaVerifyListener() {
                    @Override
                    public void onVerifyCallback(JSONObject jsonObject) {
                        try {
                            int ret = jsonObject.getInt(RequestParamConst.RET);
                            if (StatusCode.SUCCESS == ret) {
                                String ticket = jsonObject.optString(RequestParamConst.TICKET);
                                String randStr = jsonObject.optString(RequestParamConst.RAND_STR);
                                handlePhoneOrEmailSendRequest(randStr, ticket);
                                showLoadingView();
                            } else {
                                DialogUtils.showToast(getActivity(), R.string
                                        .tac_captcha_verify_failed);
                            }
                        } catch (JSONException e) {
                            DialogUtils.showToast(getActivity(), R.string
                                    .tac_captcha_verify_failed);
                        }
                    }
                }, null);
        mTCaptchaDialog.show();
    }

}
